package hikari.script;

import com.gooddies.wiring.annotations.Wire;
import com.gooddies.wiring.annotations.WiringComponent;
import hikari.utils.Utils;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Dmitry
 */
@WiringComponent
public class ScriptClassNameExtractor {

    private static Pattern classExtractorPattern = Pattern.compile("class\\s+([^\\s]+?)\\s*:\\s*public\\s+BaseHikariScript");
    @Wire
    private Utils utils;

    public ScriptClassNameExtractor() {
    }

    public String extractClassName(String path) {
        try {
            Scanner scanner = new Scanner(new File(path));
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                Matcher matcher = classExtractorPattern.matcher(line);
                if (matcher.find()) {
                    scanner.close();
                    return matcher.group(1);
                }
            }
        } catch (FileNotFoundException ex) {
            utils.logError(ex);
        }
        return null;
    }
}
